package CountDownLatchTest;

import io.netty.util.internal.ConcurrentSet;
import org.junit.Test;

import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by dycong on 2017/4/5.
 * todo 第一个类是一个启动信号，在 driver 为继续执行 worker 做好准备之前，它会阻止所有的 worker 继续执行。第二个类是一个完成信号，它允许 driver 在完成所有 worker 之前一直等待。
 */
public class CountDownLatch1 {
    private static final int N = 10;
    static CountDownLatch startSignal = new CountDownLatch(1);
    static CountDownLatch doneSignal = new CountDownLatch(N);

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < N; i++) {
            new Thread(new Worker1(startSignal, doneSignal)).start();
        }
        System.out.println("main start");
        Thread.sleep(3000);
        startSignal.countDown();
        doneSignal.await();
        System.out.println("finish");
    }

    @Test
    public void test() throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CountDownLatch startSignal = new CountDownLatch(3);
        Set<Integer> set = new ConcurrentSet<>();
        for (int i = 0; i < 3; i++) {
            executorService.submit(() -> {

                try {
                    startSignal.countDown();
                    startSignal.await();
                    while (true) {
                        int ret = (int) ((Math.random() * 9 + 1) * 100000);
                        boolean suc = set.add(ret);
                        if (!suc) {
                            System.out.println(ret);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        doneSignal.await();
    }


    @Test
    public void test2() throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        ThreadLocal<Integer> businessInfo = new ThreadLocal<>();
        for (int i = 0; i < 300000; i++) {
            executorService.submit(() -> {
            int nextInt = new Random().nextInt();
                System.out.println(businessInfo.get());
                businessInfo.set(nextInt);
            });
        }

        doneSignal.await();
    }
}
